#!/usr/bin/env python
#
# Copyright 2008 Allen Hutchison (allen@hutchison.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $URL$
__version__ = "$Rev$"
__author__ = "Allen Hutchison (allen@hutchison.org)"

import datetime
import logging

from lib.scrapers.uk.lon.tube_parser import TubeParser


from google.appengine.api import memcache

class StoreStatus():
  def __init__(self, minutes=5):
    self.date = datetime.datetime.now()
    self.elapsedTime = datetime.timedelta(0, (60 * minutes), 0)
    self.update = self.__updateNow()
    logging.info("date: %s elapsedTime: %s update %s" % 
      (self.date, self.elapsedTime, self.update))
    if self.update:
      self.parsers = [TubeParser()]
      self.data = {}
  
  def storeStatusValues(self):
    if self.update:
      for network in self.parsers:
        if not self.data.has_key(network.geography):
          self.data[network.geography] = []
        for line in network.getStatusValues():
          logging.info('Saving line: %s %s' % (network.geography, line.name))
          line.put()
          self.data[network.geography].append(line)
      self.__setMemcache()
  
  def __setMemcache(self):
    """ __setMemcache - Set data in the memcache"""
    if (self.update and (self.data is not {})):
      for geography in self.data.keys():
        memcache.set(geography + '-TIME', self.date)
        memcache.set(geography + '-DATA', self.data[geography])
      memcache.set('LAST-UPDATE-TIME', self.date)
  
  def __updateNow(self):
    """__updateNow - Boolean to determine if we should really update.
    
    We only want to update the datastore every five minutes, now matter how many
    times the store status application is called. This function looks at the
    time since the last update (stored in memcache) and determines if it's been
    enough time since the last update for us to update again.
    
    Returns:
      True - If it's time to update
      False - If it's not time to update
    """
    oldDate = memcache.get('LAST-UPDATE-TIME')
    if ((oldDate is not None) and
        ((self.date - oldDate) <= self.elapsedTime)):
      return False
    else:
      return True
